# -*- coding: utf-8 -*-

# from django.http import HttpResponse
import json

from django.core import serializers
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render

from TestModel.models import User
from TestModel.models import Grade

def index(request):
    if request.method == 'GET':
        return render(request, 'admin/index.html')
    else:
        return HttpResponse('<h1>Not found</h1><a href="/admin">返回首页</a>')

def user(request):
    if request.method == 'GET':
        return render(request, 'admin/user.html', userData())
    else:
        return HttpResponse('<h1>Not found</h1><a href="/admin">返回首页</a>')

def grade(request):
    if request.method == 'GET':
        return render(request, 'admin/grade.html', gradeData())
    else:
        return HttpResponse('<h1>Not found</h1><a href="/admin">返回首页</a>')

def insertGrade(request):
    if request.method == 'GET':
        context = {
            'user': {
            },
        }
        return render(request, 'admin/addgrade.html', (context))
    else:
        print(request.POST)
        if 'user_id' in request.POST and 'grade' in request.POST:
            adduser = Grade(user=User.objects.filter(id=request.POST['user_id'])[0], grade=request.POST['grade'])
            adduser.save()
            return HttpResponseRedirect('/admin/grade')
        context = {
            'user': {
            },
            'error': '参数有误',
        }
        return render(request, 'admin/adduser.html', context)


def userData():
    result = User.objects.all()
    data = serializers.serialize("json", result)
    context = {
        'user': {
        },
        'data': json.loads(data)
    }
    return context

def gradeData():
    result = Grade.objects.all()
    data = serializers.serialize("json", result)
    dataJson = json.loads(data)

    for grade in dataJson:
        print(grade['fields']['user'])
    result1 = User.objects.all()
    data1 = serializers.serialize("json", result1)
    users = json.loads(data1)
    for user in users:
        if user['pk'] == 1:
            print('>>>>>>>>', user["fields"]["user_name"])

    context = {
        'user': {
        },
        'data': dataJson
    }
    print(context)
    return context

# 数据库添加操作
def insertUser(request):
    if request.method == 'GET':
        context = {
            'user': {
            },
        }
        return render(request, 'admin/adduser.html', (context))
    else:
        print(request.POST)
        if 'user_name' in request.POST and \
                        'user_sex' in request.POST and \
                        'user_age' in request.POST and \
                        'user_phone' in request.POST and \
                        'user_nick' in request.POST and \
                        'user_pwd' in request.POST:

            adduser = User(user_name=request.POST['user_name'], user_sex=request.POST['user_sex'],\
                           user_age=request.POST['user_age'], user_phone=request.POST['user_phone'],
                           user_nick=request.POST['user_nick'], user_pwd=request.POST['user_pwd'])
            adduser.save()

            return HttpResponseRedirect('/admin/user')

        context = {
            'user': {
            },
            'error': '参数有误',
        }
        return render(request, 'admin/adduser.html', context)


# 数据库更新操作
def updateUser(request):
    # 修改其中一个id=1的name字段，再save，相当于SQL中的UPDATE
    test1 = User.objects.get(id=1)
    test1.name = 'Google'
    test1.save()

    # 另外一种方式
    # User.objects.filter(id=1).update(name='Google')

    # 修改所有的列
    # User.objects.all().update(name='Google')

    return HttpResponse("<p>修改成功</p>")



# 数据库删除操作
def deleteUser(request):
    # 删除id=1的数据
    # test1 = User.objects.get(id=7)
    # test1.delete()

    # 另外一种方式
    # User.objects.filter(id=1).delete()

    # 删除所有数据
    # User.objects.all().delete()

    # return HttpResponse("<p>删除成功</p>")
    if request.method == 'POST':
        context = {
            'user': {
                'user_name': 'post',
            },
        }
        return render(request, 'admin/adduser.html', (context))
    if request.method == 'GET':
        context = {
            'user': {
                'user_name': 'get',
            },
        }
        return render(request, 'admin/adduser.html', (context))


